
local TankMovement = class("TankMovement", require("unity.LuaMonoBehaviour"))

---
---m_PlayerNumber number
---m_Speed number
---m_TurnSpeed number
---m_MovementAudio AudioSource
---m_EngineIdling AudioClip
---m_EngineDriving AudioClip
---m_PitchRange number
---
function TankMovement:Awake()
    self.m_MovementAxisName = nil
    self.m_TurnAxisName = nil
    self.m_Rigidbody = nil
    self.m_MovementInputValue = 0
    self.m_TurnInputValue = 0
    self.m_OriginalPitch = 0
    self.m_particleSystems = {}

    self.m_Rigidbody = self:GetComponent("Rigidbody")
end

function TankMovement:OnEnable()
    self.m_Rigidbody.isKinematic = false
    self.m_MovementInputValue = 0
    self.m_TurnInputValue = 0
    self.m_particleSystems = self:GetComponentsInChildren(tolua.typeof(UnityEngine.ParticleSystem))
    for i,ps in table.ipairs_Array(self.m_particleSystems) do
        ps:Play()
    end
end

function TankMovement:OnDisable()
    self.m_Rigidbody.isKinematic = true
    for i,ps in table.ipairs_Array(self.m_particleSystems) do
        ps:Stop()
    end
end

function TankMovement:Start()
    self.m_MovementAxisName = "Vertical" .. tostring(self.m_PlayerNumber) 
    self.m_TurnAxisName = "Horizontal" .. tostring(self.m_PlayerNumber) 
    self.m_OriginalPitch = self.m_MovementAudio.pitch
end

function TankMovement:Update()
    self.m_MovementInputValue = UnityEngine.Input.GetAxis (self.m_MovementAxisName)
    self.m_TurnInputValue = UnityEngine.Input.GetAxis (self.m_TurnAxisName)
    self:EngineAudio ()
end

function TankMovement:EngineAudio()
    if Mathf.Abs (self.m_MovementInputValue) < 0.1 and Mathf.Abs (self.m_TurnInputValue) < 0.1 then
        if self.m_MovementAudio.clip == self.m_EngineDriving then
            self.m_MovementAudio.clip = self.m_EngineIdling
            self.m_MovementAudio.pitch = math.randRangeFloat (self.m_OriginalPitch - self.m_PitchRange, self.m_OriginalPitch + self.m_PitchRange)
            self.m_MovementAudio:Play ()
        end
    else 
        if self.m_MovementAudio.clip == self.m_EngineIdling then
            self.m_MovementAudio.clip = self.m_EngineDriving
            self.m_MovementAudio.pitch = math.randRangeFloat(self.m_OriginalPitch - self.m_PitchRange, self.m_OriginalPitch + self.m_PitchRange)
            self.m_MovementAudio:Play()
        end
    end
end

function TankMovement:FixedUpdate()
    self:Move ()
    self:Turn ()
end

function TankMovement:Move()
    local movement = self.transform.forward:Mul(self.m_MovementInputValue * self.m_Speed * Time.deltaTime)
    self.m_Rigidbody:MovePosition(self.m_Rigidbody.position + movement)
end

function TankMovement:Turn()
    local turn = self.m_TurnInputValue * self.m_TurnSpeed * Time.deltaTime
    local turnRotation = Quaternion.Euler (0, turn, 0)
    self.m_Rigidbody:MoveRotation (self.m_Rigidbody.rotation * turnRotation)
end

return TankMovement
